package com.github.binarywang.demo.wx.mp.controller;

import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.bean.oauth2.WxOAuth2AccessToken;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

/**
 * Created by dell on 2019/1/10.
 */
@Controller
@RequestMapping("wechat/{appid}")
@Slf4j
public class WechatController {

    @Value("${wx.authorizeUrl}")
    private String url;

    @Autowired
    private WxMpService wxService;

    @GetMapping("authorize")
    public String authorize(@PathVariable String appid, @RequestParam("returnurl") String returnurl){
        if (!this.wxService.switchover(appid)) {
            throw new IllegalArgumentException(String.format("未找到对应appid=[%s]的配置，请核实！", appid));
        }
        // 1.配置
        // 2.调用方法
        String redirectUrl = wxService.getOAuth2Service().buildAuthorizationUrl(url, WxConsts.OAuth2Scope.SNSAPI_USERINFO, returnurl);
        log.info("【微信网页授权】获取code，redirectUrl={}", redirectUrl);
        return "redirect:" + redirectUrl;
    }

    @GetMapping("userInfo")
    public String userInfo(@PathVariable String appid,@RequestParam("code") String code,
                         @RequestParam("state") String returnurl){
        if (!this.wxService.switchover(appid)) {
            throw new IllegalArgumentException(String.format("未找到对应appid=[%s]的配置，请核实！", appid));
        }
        WxOAuth2AccessToken accessToken=null;
        try {
            accessToken = wxService.getOAuth2Service().getAccessToken(code);
        } catch (WxErrorException e) {
            log.error("【微信网页授权】{}", e.toString());
            e.printStackTrace();
        }
        assert accessToken != null;
        String openId = accessToken.getOpenId();
        return "redirect:" + returnurl + "?openId=" + openId;
    }


}
